#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

size_t Lshell_execute(const char *cmd, char *buff, size_t buffsz);

int main(void)
{
	char *data;

	char file[1024];
    strcpy(file, "flash.XXXXXX");
    int fd = mkstemp(file);

	printf("%s\n",
		   "Content-Type:text/html;charset=iso-8859-1");
	printf("%s\n",
		   "Access-Control-Allow-Credentials: true");
	printf("%s%c%c\n",
		   "Access-Control-Allow-Origin: *", 13, 10);

	data = getenv("QUERY_STRING");
	if (data == NULL)
	{
		printf("format error\n");
		return -1;
	}
	// else
	// 	printf("%s\n", data);

	// Lshell_execute("echo 0 > flash.res", NULL, 0);
	char cmd[64] = {0};
	snprintf(cmd, sizeof(cmd) - 1, "TflashCanAddr 0 %s 2&> %s", data, file);
	Lshell_execute(cmd, NULL, 0);

	char result[256] = {0};
	// int fd = open("flash.res", O_CREAT | O_RDWR, 0666);

	while (1)
	{
		int rc = read(fd, result, sizeof(result) - 1);
		if (rc < 0)
			perror("read");
		else if (rc == 0)
			break;
	}
    unlink(file);// +
	close(fd);

	if (strstr(result, "success"))
	{
		// char imei[128] = {0};
		// Lshell_execute("cat /mnt/yaffs2/Cdatabox/test/ID", imei, sizeof(imei) - 1);
		printf("Flash:success\r\n");
		// printf("BoardId:%s\n", imei);
	}
	else
	{
		printf("Flash:operation failed\n");
		return -1;
	}

	return 0;
}

size_t Lshell_execute(const char *cmd, char *buff, size_t buffsz)
{
	FILE *read_fp;
	size_t chars_read;
	size_t left = buffsz;

	read_fp = popen(cmd, "r");
	if (read_fp == NULL)
	{
		fprintf(stderr, "__popen_once open error\n");
		return buffsz - left;
	}

	if (buff == NULL)
	{
		pclose(read_fp);
		return 0;
	}

	// memset(buff, 0x00, buffsz);
	while (left > 0)
	{
		chars_read = fread(buff, 1, buffsz, read_fp); // only 2th arg of "fread" is 1, return value equals read bytes
		if (chars_read < buffsz)
		{
			if (feof(read_fp))
			{
				clearerr(read_fp);
				left -= chars_read;
				break;
			}
			else if (ferror(read_fp))
			{
				clearerr(read_fp);
				fprintf(stderr, "__popen_once stearm error\n");
				break;
			}
		}
		buff += chars_read;
		left -= chars_read;
	}

	pclose(read_fp);
	return buffsz - left;
}